<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="Netty是一款非常优秀的网络编程框架，是对NIO的二次封装，本文将重点剖析Netty服务端的启动流程，深入底层了解如何使用NIO编程服务端。 本文是笔者基于问题的启发式源码阅读技巧的展示，建议带着如下问题开始本文的阅读：  ServerBootstrap 的 option 与 childOption 分别有什么作用 服务端IO通道如何绑定事件链。 ServerBootstrap 的 handle">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty进阶：手把手教你如何编写一个NIO服务端">
<meta property="og:url" content="https://www.codingw.net/posts/381d8256.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="Netty是一款非常优秀的网络编程框架，是对NIO的二次封装，本文将重点剖析Netty服务端的启动流程，深入底层了解如何使用NIO编程服务端。 本文是笔者基于问题的启发式源码阅读技巧的展示，建议带着如下问题开始本文的阅读：  ServerBootstrap 的 option 与 childOption 分别有什么作用 服务端IO通道如何绑定事件链。 ServerBootstrap 的 handle">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210219232527622.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210219234131283.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210221201948839.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210221205105995.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210221205717118.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210221210646200.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210221212042124.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210221213106700.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210221230446368.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210221230647160.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210221231103221.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210221231251135.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210101213844526.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="article:published_time" content="2021-02-24T14:01:59.000Z">
<meta property="article:modified_time" content="2021-04-26T12:33:08.631Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20210219232527622.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/381d8256.html"/>





  <title>Netty进阶：手把手教你如何编写一个NIO服务端 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/381d8256.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Netty进阶：手把手教你如何编写一个NIO服务端</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-02-24T22:01:59+08:00">
                2021-02-24
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/netty/" itemprop="url" rel="index">
                    <span itemprop="name">netty</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/381d8256.html" class="leancloud_visitors" data-flag-title="Netty进阶：手把手教你如何编写一个NIO服务端">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>Netty是一款非常优秀的网络编程框架，是对NIO的二次封装，本文将重点剖析Netty服务端的启动流程，深入底层了解如何使用NIO编程服务端。</p>
<p><strong>本文是笔者基于问题的启发式源码阅读技巧的展示</strong>，建议带着如下问题开始本文的阅读：</p>
<ul>
<li>ServerBootstrap 的 option 与 childOption 分别有什么作用</li>
<li>服务端IO通道如何绑定事件链。</li>
<li>ServerBootstrap 的 handler 方法与 childHandler 方法的区别又是什么？</li>
<li>childHandler中的方法在服务端bind方法时会被调用吗？</li>
</ul>
<span id="more"></span>

<h2 id="1、Netty服务端启动示例"><a href="#1、Netty服务端启动示例" class="headerlink" title="1、Netty服务端启动示例"></a>1、Netty服务端启动示例</h2><p>基于Netty的使用示例如下：<br><img src="https://img-blog.csdnimg.cn/20210219232527622.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>代码@1：创建主从多Reactor线程模型的Boss线程组，通常只需要设置一个线程，用于监听客户端的连接请求(OP_ACCEPT)。</p>
<p>代码@2：创建主从多Reactor线程模型的Work线程组，即IO线程组，默认为CPU核数的两倍。</p>
<p>代码@3：创建Netty服务端启动工具类ServerBootstrap。</p>
<p>代码@4：调用group方法设置主从线程组。</p>
<p>代码@5：设置通道的类型，服务端NIO通道类型 NioServerSocketChannel。</p>
<p>代码@6：通过option方法为通道服务端通道选项。</p>
<p>代码@7：通过chiildOption方法为IO通道设置选项。</p>
<p>代码@8：通过ChannelInitializer添加自定义的ChannelHandler，通常包括编码解码器、业务Handler。</p>
<p>代码@9：调用管道的addLast添加自定义编码解码器。</p>
<p>代码@10：调用bind方法绑定到服务端指定接口，绑定完成后则在指点端口上监听客户端的连接。</p>
<p>服务端的核心流程入口为bind方法，接下来我们将详细分析其实现原理，继续体会NIO编程技巧。</p>
<h2 id="2、Netty服务端启动流程"><a href="#2、Netty服务端启动流程" class="headerlink" title="2、Netty服务端启动流程"></a>2、Netty服务端启动流程</h2><p>通过跟踪其bind方法，最终将进入到AbstractBootstrap的doBind方法。<br><img src="https://img-blog.csdnimg.cn/20210219234131283.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>其关键实现点：<br>代码@1：通过调用initAndRegister方法完成底层网络初始化与通道注册工作。<br>代码@2：如果初始化与注册工作已完成，则直接调用doBind0方法完成绑定操作。<br>代码@3：如果初始化与注册工作未完成，则通过regFuture（注册凭证）中添加监听器，等注册完成后再执行doBind0方法。</p>
<blockquote>
<p>技巧提示：基于Future异步编程，在主线程中通过调用future.isDone方法判断异步方法是否已完成，如果未完成，通过在该凭证上添加监听器（事件回调），操作完成后执行回调逻辑。</p>
</blockquote>
<p>从上面的方法来看服务端的绑定流程包<strong>含初始化与绑定两个子流程</strong>，接下来将分别深入探讨。</p>
<h4 id="2-1-通道初始化"><a href="#2-1-通道初始化" class="headerlink" title="2.1 通道初始化"></a>2.1 通道初始化</h4><p>基于NIO编程，需要先创建通道，然后将其注册到<strong>事件选择器</strong>，这个过程由 AbstractBootstrap 的 initAndRegister 方法实现。<br><img src="https://img-blog.csdnimg.cn/20210221201948839.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>实现的关键点如下：<br>代码@1：创建NIO服务端通道实现类NioServerSocketChannel的实例。</p>
<p>代码@2：调用 init 方法初始化通道。</p>
<p>代码@3：将通道注册到事件轮询器EventLoopGroup</p>
<p>代码@4：:如果通道已注册，但发生了错误则调用通道close方法回收相关资源，如果未注册成功，则强制清除通道占用的资源，特别是文件占用符。</p>
<p>关于通道的注册逻辑已经在<a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/112972761">手把手教你如何编写一个NIO客户端</a> 中已详细介绍，故接下来重点关注一下服务端通道的注册流程。</p>
<h5 id="2-1-1-服务端通道初始化流程"><a href="#2-1-1-服务端通道初始化流程" class="headerlink" title="2.1.1 服务端通道初始化流程"></a>2.1.1 服务端通道初始化流程</h5><p>AbstractBootstrap 的 init 方法是一个抽象方法，具体有其子类实现：<br><img src="https://img-blog.csdnimg.cn/20210221205105995.png#pic_center" alt="在这里插入图片描述"><br>服务端通道的初始化代码由ServerBootstrap的init方法。<br><img src="https://img-blog.csdnimg.cn/20210221205717118.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>Step1：首先将通过ServerBootstrap设置的选项与附加选项初始化到通道中。<br><img src="https://img-blog.csdnimg.cn/20210221210646200.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>Step2：<strong>init 方法的关键点</strong>：将 handler 方法设置的事件链，同时新增  <strong>ServerBootstrapAcceptor</strong>  事件处理方法加入到 NioServerSocketChannel 的事件链，但并没有把 childHandler 中添加的事件链添加到NioServerSocketChannel。</p>
<p><strong>读者朋友们，请停下来思考一下，为什么会这样？从现在可以肯定的是 handler 方法定义的事件处理方法将在与 NioServerSocketChannel 相关的事件发生时其作用。</strong></p>
<p>要解开这个谜题，我们有必要来看看 ServerBootstrapAcceptor 是如何工作的。</p>
<h5 id="2-1-2-ServerBootstrapAcceptor-详解"><a href="#2-1-2-ServerBootstrapAcceptor-详解" class="headerlink" title="2.1.2 ServerBootstrapAcceptor 详解"></a>2.1.2 ServerBootstrapAcceptor 详解</h5><p>ServerBootstrapAcceptor 类图如下所示：<br><img src="https://img-blog.csdnimg.cn/20210221212042124.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>ServerBootstrapAcceptor方法只实现了inbound事件的channelRead事件。在详细探究它之前先看看属性：</p>
<ul>
<li>EventLoopGroup childGroup<br>事件执行器组，ServerBootstrap设置的从Reactor线程组，即Work线程组。</li>
<li>ChannelHandler childHandler<br>ServerBootstrap#childHandler 设置的事件处理器，也就是用户定义的事件处理器。</li>
</ul>
<p>接下来探究其 channelRead 方法的实现逻辑：<br><img src="https://img-blog.csdnimg.cn/20210221213106700.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>Step1：channelRead竟然传入的是一个Channel，那这个Channel对象是NioSocketChannel吗？</p>
<p>是的，原来当 OP_ACCEPT 事件触发后，Server端会通过调用ServerSocketChannel 的 accept()方法，将返回一个 NioSocketChannel，读写操作的载体，在NIO中负责数据的读写。</p>
<p>Step2：将通过 childHandler 定义的事件处理器绑定到 NioSocketChannel。</p>
<p>最终完成 NioServerSocketChannel 与 NioSocketChannel 的初始化与事件绑定。</p>
<p>关于 NioSocketChannel 详细的初始化流程蕴含在 ChannelInitializer，其机制已经在 <a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/112972761">手把手教你如何编写一个NIO客户端</a>  中详细介绍。</p>
<h4 id="2-2-NIO绑定机制"><a href="#2-2-NIO绑定机制" class="headerlink" title="2.2 NIO绑定机制"></a>2.2 NIO绑定机制</h4><p>在通道完成初始化与注册后，服务端需要进行端口绑定，由 AbstractBootstrap 的 doBind0 方法实现。<br><img src="https://img-blog.csdnimg.cn/20210221230446368.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>bind 的核心实现最终是调用 Channel 的 bind 方法，最终由 AbstractChannel 类实现：<br><img src="https://img-blog.csdnimg.cn/20210221230647160.png#pic_center" alt="在这里插入图片描述"><br>bind事件将传播，根据Netty事件传播机制，bind 属于 ChannelOutbound事件，最终将调用 HeadContext的bind方法，最终将调用Unsafe的bind方法，更加具体是调用 AbstractChannel的内部类AbstractUnsafe的bind方法，其代码如下所示：<br><img src="https://img-blog.csdnimg.cn/20210221231103221.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>doBind 方法是一个抽象方法，NIO服务端的实现：NioServerSocketChannel。<br><img src="https://img-blog.csdnimg.cn/20210221231251135.png" alt="在这里插入图片描述"><br>即最终通过调用NIO底层NioServerSocketChannel 的 bind 方法完成服务端通道的绑定操作，即实现服务端在特定端口监听客户客户端的连接请求。</p>
<p><strong>行文至此开头部门提出的问题大家都能解答了不</strong>，为了倒逼读者朋友门真正能理解开头部分的问题，<strong>建议读者进行总结，真正做到带着问题阅读源码</strong>，当然可以加笔者私信：dingwpmz，共同交流探讨。</p>
<hr>
<p>欢迎加笔者微信号(<strong>dingwpmz</strong>)，拉您如技术交流加群探讨，关注『中间件兴趣圈』回复<strong>【PDF】</strong>可获取海量学习资料。<br><img src="https://img-blog.csdnimg.cn/20210101213844526.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/ea6d8964.html" rel="next" title="面试时遇到一致性哈希算法这样回答会让面试官眼前一亮">
                <i class="fa fa-chevron-left"></i> 面试时遇到一致性哈希算法这样回答会让面试官眼前一亮
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/b6f85d12.html" rel="prev" title="事务消息应用场景、实现原理与项目实战(附全部源码)">
                事务消息应用场景、实现原理与项目实战(附全部源码) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81Netty%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%90%AF%E5%8A%A8%E7%A4%BA%E4%BE%8B"><span class="nav-number">1.</span> <span class="nav-text">1、Netty服务端启动示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81Netty%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%90%AF%E5%8A%A8%E6%B5%81%E7%A8%8B"><span class="nav-number">2.</span> <span class="nav-text">2、Netty服务端启动流程</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-%E9%80%9A%E9%81%93%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="nav-number">2.0.1.</span> <span class="nav-text">2.1 通道初始化</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#2-1-1-%E6%9C%8D%E5%8A%A1%E7%AB%AF%E9%80%9A%E9%81%93%E5%88%9D%E5%A7%8B%E5%8C%96%E6%B5%81%E7%A8%8B"><span class="nav-number">2.0.1.1.</span> <span class="nav-text">2.1.1 服务端通道初始化流程</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-1-2-ServerBootstrapAcceptor-%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.0.1.2.</span> <span class="nav-text">2.1.2 ServerBootstrapAcceptor 详解</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-NIO%E7%BB%91%E5%AE%9A%E6%9C%BA%E5%88%B6"><span class="nav-number">2.0.2.</span> <span class="nav-text">2.2 NIO绑定机制</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
